﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using MyMoviesBrowserLibrary;
using System.Windows.Threading;

namespace TVManager
{
    /// <summary>
    /// Interaction logic for TVSeriesControl.xaml
    /// </summary>
    public delegate void SeriesUpdatedEvent(Series series);
    public delegate void StatusUpdatedEvent(string statusText, bool showControl, bool isIndeterminate, int percent);
    public partial class TVSeriesControl : UserControl
    {
        public event SeriesUpdatedEvent SeriesUpdated;
        public event StatusUpdatedEvent StatusUpdated;

        public Series Series
        {
            get { return DataContext as Series; }
            set
            {
                DataContext = value;
                if (value == null)
                    return;

                if (value.FirstAired.HasValue)
                    firstAiredTextBlock.Text = value.FirstAired.Value.ToString("MMMM d, yyyy");
                if (value.Runtime.HasValue)
                {
                    runtimeTextBlock.Text = "";
                    TimeSpan runtime = TimeSpan.FromMinutes(value.Runtime.Value);
                    if (runtime.Hours > 0)
                        runtimeTextBlock.Text = string.Format("{0} hours ", runtime.Hours);
                    if (runtime.Minutes > 0)
                        runtimeTextBlock.Text += string.Format("{0} minutes ", runtime.Minutes);
                }

                if (value.Series_Genres.Count > 0)
                {
                    genresTextBlock.Text = string.Join(", ", value.Series_Genres.Select(s => s.Genre.GenreDesc).ToArray());
                }

                if (value != null)
                    mainLayout.Visibility = Visibility.Visible;
                else
                    mainLayout.Visibility = Visibility.Collapsed;

                SetSeasonsListBox();
                actorsListBox.ItemsSource = value.Series_Persons.OrderBy(s => s.SortOrder).ThenBy(s => s.Person.PersonName);


                LoadImages();
            }
        }
        private TVManagerBusinessLayer bl = new TVManagerBusinessLayer();
        public TVSeriesControl()
        {
            InitializeComponent();
            changePosterButton.Click += new RoutedEventHandler(changeBannerButton_Click);
            changeBannerButton.Click += new RoutedEventHandler(changeBannerButton_Click);
            changeFanartButton.Click += new RoutedEventHandler(changeBannerButton_Click);
            viewSeasonButton.Click += new RoutedEventHandler(viewSeasonButton_Click);
            refreshFilesButton.Click += new RoutedEventHandler(refreshFilesButton_Click);
            updateSeriesButton.Click += new RoutedEventHandler(updateSeriesButton_Click);

            seasonsListBox.MouseDoubleClick += new MouseButtonEventHandler(seasonsListBox_MouseDoubleClick);

            displaySeasonsCheckbox.Click += new RoutedEventHandler(displaySeasonsCheckbox_Click);
            displaySeasonsCheckbox.IsChecked = Settings.Default.HideSeasonsWithoutFiles;

            mainLayout.Drop += new DragEventHandler(mainLayout_Drop);
            bl.AddFilesToSeriesCompleted += new AddFilesToSeriesEvent(bl_AddFilesToSeriesCompleted);
            bl.DataUpdated += new UpdateEvent(bl_DataUpdated);
            bl.AddSeriesCompleted += new AddSeriesEvent(bl_AddSeriesCompleted);
            bl.UpdateEpisodeFilesCompleted += new UpdateEpisodeFilesEvent(bl_UpdateEpisodeFilesCompleted);
        }

        void bl_UpdateEpisodeFilesCompleted(List<Episode> episodes)
        {
            foreach (Episode episode in episodes)
            {
                Episode ep = Series.Episodes.SingleOrDefault(e2 => e2.EpisodeId == episode.EpisodeId);
                if (ep != null)
                    ep.FileLocation = episode.FileLocation;
            }
            if (StatusUpdated != null)
                StatusUpdated("", false, true,0);
            
        }

        void bl_AddSeriesCompleted(Series series)
        {
            Series = series;
            if (SeriesUpdated != null)
                SeriesUpdated(series);
            if (StatusUpdated != null)
                StatusUpdated("", false, true,0);
            
        }

        void bl_DataUpdated(string updateText)
        {
            if (StatusUpdated != null)
                StatusUpdated(updateText, true,true,0);
        }

        void updateSeriesButton_Click(object sender, RoutedEventArgs e)
        {
            if (StatusUpdated != null)
                StatusUpdated("", true,true,0);
            bl.AddSeriesAsync(Series.SeriesId, Series.FolderLocation);
        }

        void bl_AddFilesToSeriesCompleted(List<Episode> episodes)
        {
            episodes.RemoveAll(ep => ep == null);
            foreach (Episode episode in episodes)
            {
                Episode ep = Series.Episodes.SingleOrDefault(e2 => e2.EpisodeId == episode.EpisodeId);
                if (ep != null)
                    ep.FileLocation = episode.FileLocation;
            }
            SetSeasonsListBox();
            if (StatusUpdated != null)
                StatusUpdated("", false,true,0);
        }

        void displaySeasonsCheckbox_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.HideSeasonsWithoutFiles = displaySeasonsCheckbox.IsChecked.Value;
            Settings.Default.Save();
            SetSeasonsListBox();
        }

        void SetSeasonsListBox()
        {
            seasonsListBox.ItemsSource = Series.Seasons.Where(s => !displaySeasonsCheckbox.IsChecked.Value
                || (displaySeasonsCheckbox.IsChecked.Value && s.Episodes.Where(e => !string.IsNullOrEmpty(e.FileLocation)).Count() > 0)).OrderBy(s => s.SeasonNumber);
        }
        void refreshFilesButton_Click(object sender, RoutedEventArgs e)
        {
            if (StatusUpdated != null)
                StatusUpdated("Updating Files", true,true,0);
            bl.UpdateEpisodeFilesAsync(Series.SeriesId);
        }

        void mainLayout_Drop(object sender, DragEventArgs e)
        {
            if (e.Data is System.Windows.DataObject && ((System.Windows.DataObject)e.Data).ContainsFileDropList())
            {
                if (StatusUpdated != null)
                    StatusUpdated("Adding File(s)", true,true,0);
                List<string> filenames = new List<string>();
                foreach (string filename in ((System.Windows.DataObject)e.Data).GetFileDropList())
                    filenames.Add(filename);
                bl.AddFilesToSeriesAsync(filenames, Series.SeriesId, null);
            }
        }

        void seasonsListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewSeason();
        }

        void viewSeasonButton_Click(object sender, RoutedEventArgs e)
        {
            ViewSeason();
        }

        void ViewSeason()
        {
            Season season = seasonsListBox.SelectedValue as Season;
            if (season != null)
            {
                SeasonWindow seasonWindow = new SeasonWindow() { Season = season };
                seasonWindow.ShowDialog();
            }
        }

        void changeBannerButton_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            ChooseImageWindow chooseImageWindow = new ChooseImageWindow();
            chooseImageWindow.Series = Series;
            chooseImageWindow.BannerType = button.Tag.ToString();
            chooseImageWindow.BannerSelected += new BannerSelectedEvent(chooseImageWindow_BannerSelected);
            chooseImageWindow.ShowDialog();
        }

        void chooseImageWindow_BannerSelected(object sender, string bannerUrl, string bannerType)
        {
            if (StatusUpdated != null)
                StatusUpdated("Loading Image", true,true,0);
            string fileLocation = "";
            switch (bannerType)
            {
                case "poster":
                    posterImage.Source = null;
                    fileLocation = System.IO.Path.Combine(Series.FolderLocation, "folder.jpg");
                    break;
                case "series":
                    bannerImage.Source = null;
                    fileLocation = System.IO.Path.Combine(Series.FolderLocation, "banner.jpg");
                    break;
                case "fanart":
                    fanartImage.Source = null;
                    fileLocation = System.IO.Path.Combine(Series.FolderLocation, "fanart.jpg");
                    break;
                default:
                    return;
                    break;
            }

            WebClient client = new WebClient();
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            if (StatusUpdated != null)
                StatusUpdated("Downloading Image", true,false,0);

            client.DownloadFileAsync(new Uri(bannerUrl), fileLocation);

        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (StatusUpdated != null)
                StatusUpdated("Downloading Image", true, false, e.ProgressPercentage);
        }

        void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("There was an error downloading image.");
            }
            else
                LoadImages();
            if (StatusUpdated != null)
                StatusUpdated("", false, false, 0);
        }

        private void LoadImages()
        {
            if (Series == null)
                return;
            string bannerFile = System.IO.Path.Combine(Series.FolderLocation, "banner.jpg");
            if (File.Exists(bannerFile))
            {
                //Uri uri = new Uri("file://" +bannerFile, UriKind.RelativeOrAbsolute);
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = new MemoryStream(File.ReadAllBytes(bannerFile));
                bitmap.EndInit();
                bannerImage.Source = bitmap;
            }

            string posterFile = System.IO.Path.Combine(Series.FolderLocation, "folder.jpg");
            if (File.Exists(posterFile))
            {
                //Uri uri = new Uri("file://" + posterFile, UriKind.RelativeOrAbsolute);
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = new MemoryStream(File.ReadAllBytes(posterFile));
                bitmap.EndInit();
                posterImage.Source = bitmap;
            }

            string fanartFile = System.IO.Path.Combine(Series.FolderLocation, "fanart.jpg");
            if (File.Exists(fanartFile))
            {
                //Uri uri = new Uri("file://" + fanartFile, UriKind.RelativeOrAbsolute);
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = new MemoryStream(File.ReadAllBytes(fanartFile));
                bitmap.EndInit();
                fanartImage.Source = bitmap;
            }
        }
    }
}
